package com.zbw.printlibrary.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.Log;

import java.nio.ByteBuffer;

public class BitmapUtil {
    public static final byte ESC = 0x1B;// Escape


    /**
     * 将图片转换成POS机能打印的byte[]类型
     *
     * @param bm
     * @return
     */
    public static byte[] genBitmapCode(Bitmap bm) {
        int w = bm.getWidth();
        int h = bm.getHeight();
//        if(w > MAX_BIT_WIDTH)
//            w = MAX_BIT_WIDTH;
        int bitw = ((w + 7) / 8) * 8;
        int bith = h;
        int pitch = bitw / 8;
        byte[] cmd = {0x1D, 0x76, 0x30, 0x00, (byte) (pitch & 0xff), (byte) ((pitch >> 8) & 0xff), (byte) (bith & 0xff), (byte) ((bith >> 8) & 0xff)};
        byte[] bits = new byte[bith * pitch];
        for (int y = 0; y < h; y++) {
            for (int x = 0; x < w; x++) {
                int color = bm.getPixel(x, y);
                if ((color & 0xFF) < 128) {
                    bits[y * pitch + x / 8] |= (0x80 >> (x % 8));
                }
            }
        }

        ByteBuffer bb = ByteBuffer.allocate(cmd.length + bits.length);
        bb.put(cmd);
        bb.put(bits);

        return bb.array();
    }

    /**
     * 居左
     */
    public static byte[] alignLeft() {
        byte[] result = new byte[3];
        result[0] = ESC;
        result[1] = 97;
        result[2] = 0;
        return result;
    }

    /**
     * 居中对齐
     */
    public static byte[] alignCenter() {
        byte[] result = new byte[3];
        result[0] = ESC;
        result[1] = 97;
        result[2] = 1;
        return result;
    }

    /**
     * 居右
     */
    public static byte[] alignRight() {
        byte[] result = new byte[3];
        result[0] = ESC;
        result[1] = 97;
        result[2] = 2;
        return result;
    }

    /**
     * 设置字体大小
     * @param textSize
     * @return
     */
    public static byte[] setTextSize(int textSize){
        String _cmdstr = "";
        switch (textSize){
            case 1:
                _cmdstr = new StringBuffer().append((char) 29).append((char) 33)
                        .append((char) 17).toString();
                break;
            case 2:
                _cmdstr = new StringBuffer().append((char) 29).append((char) 33)
                        .append((char) 34).toString();
                break;
            default:
                _cmdstr = new StringBuffer().append((char) 29).append((char) 33)
                        .append((char) 0).toString();// 29 33
                break;
        }
        return _cmdstr.getBytes();
    }
}
